package com.bulletelc.apollopre.module.main.center.address.edit;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.OptionsPickerView;
import com.bulletelc.apollopre.R;
import com.bulletelc.apollopre.constants.IntentCode;
import com.bulletelc.apollopre.entity.AddressDetailBean;
import com.bulletelc.apollopre.entity.JsonBean;
import com.bulletelc.apollopre.framework.MVPBaseActivity;
import com.bulletelc.apollopre.utils.GetJsonDataUtil;
import com.bulletelc.apollopre.utils.KeyboardUtil;
import com.bulletelc.apollopre.utils.ToastUtil;
import com.bulletelc.apollopre.widget.FoolBar;
import com.google.gson.Gson;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * author: lhl
 * date  : 2018/01/23
 * desc  : 添加/编辑地址
 */

public class EditAddressActivity extends MVPBaseActivity<EditAddressContract.View,
        EditAddressPresenter> implements EditAddressContract.View, View.OnClickListener, FoolBar.ClickCallback{

    // views
    private FoolBar flBar;
    private TextView tvShow;
    private LinearLayout llPick;
    private EditText etName, etPhone, etDetail;
    private CheckBox cbIsDefault;
    private Button btnPost;

    // data
    private boolean commited = false; //是否提交过了
    private static final int MSG_LOAD_SUCCESS = 0x0002;
    private static final int MSG_LOAD_FAILED = 0x0003;
    private int addressId = 0; //地址ID
    final static int REQUEST_CODE = 1; // Intent打开Activity
    private String provinceId; // 省份ID
    private String cityId; // 城市ID
    private String districtId; // 区(县)ID
    private boolean load = false; // 地区数据是否加载好
    private List<JsonBean> options1Items = new ArrayList<>();
    private List<List<JsonBean.CityListBean>> options2Items = new ArrayList<>();
    private List<List<List<JsonBean.CityListBean.DistrictListBean>>> options3Items = new ArrayList<>();

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_LOAD_SUCCESS:
                    load = true;
                    break;

                case MSG_LOAD_FAILED:
                    Toast.makeText(EditAddressActivity.this, "地区数据解析错误", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };

    @Override
    public int getLayoutRes() {
        return R.layout.address_form_activity;

    }

    @Override
    public void assignViews() {
        flBar = findView(R.id.flBar);
        etName = findViewById(R.id.et_name);
        etPhone = findViewById(R.id.et_phone);
        llPick = findViewById(R.id.ll_pick);
        tvShow = findViewById(R.id.tv_show);
        etDetail = findViewById(R.id.et_detail);
        cbIsDefault = findView(R.id.cbIsDefault);
        btnPost = findViewById(R.id.btn_post);
    }


    @Override
    public void setListener() {
        flBar.setClickCallback(this);
        llPick.setOnClickListener(this);
        btnPost.setOnClickListener(this);
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        Intent intent = getIntent();
        if (intent != null) {
            addressId = intent.getIntExtra(IntentCode.EXTRA_KEY_ADDRESS_ID, 0);
        }

        loadData();

        if (addressId == 0) {//添加地址
            flBar.setTitle("添加地址");
        } else {//编辑地址
            flBar.setTitle("编辑地址");
            presenter.getAddressDetail(addressId);
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data == null) {
            return;
        }
        if (requestCode == REQUEST_CODE) {
            tvShow.setText(data.getStringExtra("province") + " " + data.getStringExtra("city") + " " + data.getStringExtra("district"));
        }
    }

    @Override
    protected EditAddressPresenter createPresenter() {
        return new EditAddressPresenter();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {

            case R.id.ll_pick:
                KeyboardUtil.closeKeyboard(this);
                if (load) {
                    ShowPickerView();
                } else {
                    Toast.makeText(this, "地区数据加载中，请您稍等片刻...", Toast.LENGTH_LONG).show();
                }
                break;

            case R.id.btn_post:
                if (addressId == 0) {
                    addAddress();
                } else {
                    editAddress();
                }
                break;
        }
    }

    @Override
    public void onSuccessAddAddress() {
        setResult(IntentCode.RESULT_CODE_ADD_ADDRESS_TO_LIST);
        finish();
    }

    @Override
    public void onFailAddAddress(String fail) {
        Toast.makeText(this, fail, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onErrorAddAddress(String error) {
        ToastUtil.showLongToast(this,R.string.network_msg);
    }

    @Override
    public void onSuccessEditAddress() {
        setResult(IntentCode.RESULT_CODE_ADD_ADDRESS_TO_LIST);
        finish();
    }

    @Override
    public void onFailEditAddress(String fail) {
        Toast.makeText(this, fail, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onErrorEditAddress(String error) {
        ToastUtil.showLongToast(this,R.string.network_msg);
    }

    @Override
    public void onSuccessAddressDetail(AddressDetailBean addressDetailBean) {
        if (addressDetailBean != null) {
            etName.setText(addressDetailBean.getUserName());
            etPhone.setText(addressDetailBean.getPhone_no());
            etDetail.setText(addressDetailBean.getApartment_address());
            tvShow.setText(addressDetailBean.getRegion_label());
            cbIsDefault.setChecked(isDefault(addressDetailBean.getIs_default()));
            provinceId = String.valueOf(addressDetailBean.getProvince_id());
            cityId = String.valueOf(addressDetailBean.getCity_id());
            districtId = String.valueOf(addressDetailBean.getDistrict_id());

        } else {
            Toast.makeText(this, "数据有误", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onFailAddressDetail(String fail) {
        Toast.makeText(this, fail, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onErrorAddressDetail(String error) {
        ToastUtil.showLongToast(this,R.string.network_msg);
    }

    /**
     * 添加地址
     */
    private void addAddress() {
        if (commited == false) {
            String name=etName.getText().toString().trim();
            String phone = etPhone.getText().toString().trim();
            String show = tvShow.getText().toString().trim();
            String detail=etDetail.getText().toString().trim();

            if (name == null || name.length() == 0) {
                etName.setError("请输入收货人");
                return;
            }

            if (phone == null || phone.length() == 0) {
                etPhone.setError("请输入联系电话");
                return;
            }

            if (show == null || show.length() == 0) {
                etPhone.setError("请选择地区");
                return;
            }

            if (detail == null || detail.length() ==0) {
                etDetail.setError("请输入详细地址");
                return;
            }

            int isDefault = isDefault(cbIsDefault.isChecked());

            String json;
            JSONObject subOjb = new JSONObject();
            JSONObject object = new JSONObject();
            try {
                subOjb.put("customer_name", name);
                subOjb.put("province_id", provinceId);
                subOjb.put("city_id", cityId);
                subOjb.put("district_id", districtId);
                subOjb.put("apartment_address", detail);
                subOjb.put("phone_no", phone);
                subOjb.put("is_default", isDefault);
                object.put("AddressForm", subOjb);

            } catch (JSONException e) {
                e.printStackTrace();
            }
            json = object.toString();
            presenter.addAddress(json);
            commited = true; // 改变提交状态防止多次点击
        } else {
            return;
        }

    }

    /**
     * 编辑地址
     */
    private void editAddress() {
        if (commited == false) {
            String name=etName.getText().toString().trim();
            String phone = etPhone.getText().toString().trim();
            String show = tvShow.getText().toString().trim();
            String detail=etDetail.getText().toString().trim();

            if (name == null || name.length() == 0) {
                etName.setError("请输入收货人");
                return;
            }

            if (phone == null || phone.length() == 0) {
                etPhone.setError("请输入联系电话");
                return;
            }

            if (show == null || show.length() == 0) {
                etPhone.setError("请选择地区");
                return;
            }

            if (detail == null || detail.length() ==0) {
                etDetail.setError("请输入详细地址");
                return;
            }

            int isDefault = isDefault(cbIsDefault.isChecked());

            String json;
            JSONObject subOjb = new JSONObject();
            JSONObject object = new JSONObject();
            try {
                subOjb.put("add_id", addressId);
                subOjb.put("customer_name", name);
                subOjb.put("province_id", provinceId);
                subOjb.put("city_id", cityId);
                subOjb.put("district_id", districtId);
                subOjb.put("apartment_address", detail);
                subOjb.put("phone_no", phone);
                subOjb.put("is_default", isDefault);
                object.put("AddressForm", subOjb);

            } catch (JSONException e) {
                e.printStackTrace();
            }
            json = object.toString();
            presenter.editAddress(json,addressId);
            commited = true;// 改变提交状态防止多次点击
        } else {
            return;
        }

    }

    /**
     * 判断是否默认
     *
     * @param isDefault
     * @return
     */
    private boolean isDefault(int isDefault) {
        return isDefault == 1 ? true : false;
    }

    /**
     * 判断是否默认
     * @param isChecked
     * @return
     */
    private int isDefault(boolean isChecked) {
        return isChecked ? 1 : 0;
    }

    /**
     * 开启线程 加载本地全国数据
     */
    private void loadData() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                initJsonData();
            }
        }).start();
    }

    /**
     * 加载本地全国数据
     */
    private void initJsonData() {
        String jsonData = new GetJsonDataUtil().getJson(this, "address.json");//获取assets目录下的json文件数据
        List<JsonBean> jsonBeans = parseData(jsonData);
        options1Items = jsonBeans;
        for (int i = 0; i < jsonBeans.size(); i++) {//遍历省份
            List<JsonBean.CityListBean> cityListBeans = new ArrayList<>();//该省的城市列表（第二级）
            List<List<JsonBean.CityListBean.DistrictListBean>> districtListBeans = new ArrayList<>();//该省的所有地区列表（第三极）

            for (int c = 0; c < jsonBeans.get(i).getCityList().size(); c++) {//遍历该省份的所有城市
                JsonBean.CityListBean cityListBean = jsonBeans.get(i).getCityList().get(c);
                cityListBeans.add(cityListBean);//添加城市

                List<JsonBean.CityListBean.DistrictListBean> districtListBeans1 = new ArrayList<>();//该城市的所有地区列表

                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (jsonBeans.get(i).getCityList().get(c).getDistrictList() == null || jsonBeans.get(i).getCityList().get(c).getDistrictList().size() == 0) {
                    districtListBeans1.add(null);
                } else {

                    for (int d = 0; d < jsonBeans.get(i).getCityList().get(c).getDistrictList().size(); d++) {//该城市对应地区所有数据
                        JsonBean.CityListBean.DistrictListBean district = jsonBeans.get(i).getCityList().get(c).getDistrictList().get(d);
                        districtListBeans1.add(district);//添加该城市所有地区数据
                    }
                }
                districtListBeans.add(districtListBeans1);//添加该省所有地区数据
            }

            /**
             * 添加城市数据
             */
            options2Items.add(cityListBeans);

            /**
             * 添加地区数据
             */
            options3Items.add(districtListBeans);
        }


        handler.sendEmptyMessage(MSG_LOAD_SUCCESS);

    }

    /**
     * Gson 解析
     *
     * @param result
     * @return
     */
    private List<JsonBean> parseData(String result) {
        List<JsonBean> detail = new ArrayList<>();
        try {
            JSONArray data = new JSONArray(result);
            Gson gson = new Gson();
            for (int i = 0; i < data.length(); i++) {
                JsonBean entity = gson.fromJson(data.optJSONObject(i).toString(), JsonBean.class);
                detail.add(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
            handler.sendEmptyMessage(MSG_LOAD_FAILED);
        }
        return detail;
    }

    /**
     * 弹出选择器
     */
    private void ShowPickerView() {

        OptionsPickerView pvOptions = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                String tx=null;
                if (options3Items.get(options1).get(options2).get(options3) != null) {
                    tx = options1Items.get(options1).getName() + " " +
                            options2Items.get(options1).get(options2).getName() + " " +
                            options3Items.get(options1).get(options2).get(options3).getName();

                    provinceId = String.valueOf(options1Items.get(options1).getId());
                    cityId = String.valueOf(options2Items.get(options1).get(options2).getId());
                    districtId = String.valueOf(options3Items.get(options1).get(options2).get(options3).getId());
                } else {
                    tx = options1Items.get(options1).getName() + " " +
                            options2Items.get(options1).get(options2).getName() ;

                    provinceId = String.valueOf(options1Items.get(options1).getId());
                    cityId = String.valueOf(options2Items.get(options1).get(options2).getId());
                    //districtId = String.valueOf(options3Items.get(options1).get(options2).get(options3).getId());
                }


                tvShow.setText(tx);

            }
        })

                .setTitleText("城市选择")
                .setDividerColor(Color.BLACK)
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(20)
                .build();

        /*pvOptions.setPicker(options1Items);//一级选择器
        pvOptions.setPicker(options1Items, options2Items);//二级选择器*/
        pvOptions.setPicker(options1Items, options2Items, options3Items);//三级选择器
        pvOptions.show();
    }

    @Override
    public void onLeftClick() {
        finish();
    }

    @Override
    public void onRightClick() {

    }
}
